#!/usr/bin/python3
from openpyxl import load_workbook
from openpyxl.worksheet.hyperlink import Hyperlink
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Table_Rename(Base_Plugin):
    """表重命名的插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.rename_delimiter = "->"

    def is_rename_table_name(self, sheet):
        """
        判断表名是否发生变化
        """
        return self.rename_delimiter in sheet["A2"].value

    def is_rename_table_description(self, sheet):
        """
        判断表描述是否发生变化
        """
        return self.rename_delimiter in sheet["A1"].value

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        for row in _directory.rows:
            if row[0].row < self.project_config["通用开始行"]:
                continue

            table_name = row[1].value
            if table_name is None:
                break
            assert " " not in table_name, self.error_log(
                f"""{table_name}表名中出现空格"""
            )
            table_description = row[2].value.strip()

            if self.is_rename_table_name(workbook[table_description]):
                # 修改目录表名
                row[1].value = workbook[table_description]["A2"].value.split(
                    self.rename_delimiter
                )[1]
                self.processed += 1
            if self.is_rename_table_description(workbook[table_description]):
                # 修改目录表描述
                row[2].value = workbook[table_description]["A1"].value.split(
                    self.rename_delimiter
                )[1]
                # 修改工作表名
                workbook[table_description].title = row[2].value
                # 重设超链接
                row[1].hyperlink = Hyperlink(
                    ref=f"'{row[2].value}'!A1)",
                    location=f"'{row[2].value}'!A1",
                )
                self.processed += 1

        return_val = None
        if self.processed > 0:
            saved_name = r"TableRenamed.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
